<template>
  <Dialog
    :title="title"
    :visible.sync="propVisible"
    @close="close"
    :width="400"
  >
    <el-form
      :model="ratioData"
      :rules="ratioRules"
      ref="ratioForm"
      class="u-pt20 u-pl20 u-pr20"
    >
      <el-form-item prop="ratio">
        <el-input
          placeholder="0.01~100"
          v-model="ratioData.ratio"
        >
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
    </el-form>
    <Tip
      v-if="tip"
      class="u-pl20 u-pb20 u-fs14"
    >{{tip}}</Tip>
    <el-row
      type="flex"
      justify="center"
      class="u-pb20"
    >
      <el-button
        type="primary"
        size="small"
        @click="confirm"
      >确 定</el-button>
      <el-button
        class="u-ml20"
        size="small"
        @click="close"
      >关 闭</el-button>
    </el-row>
  </Dialog>
</template>

<script>
import Dialog from "@/components/dialog";
import Tip from "@/components/tip";

export default {
  name: "DialogRatio",
  components: {
    Dialog,
    Tip
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ""
    },
    tip: {
      type: String,
      default: ""
    }
  },
  watch: {
    visible(v) {
      this.propVisible = v;
    }
  },
  data() {
    return {
      //  比例设置
      propVisible: this.visible,
      ratioData: {
        ratio: ""
      },
      ratioRules: {
        ratio: {
          required: true,
          validator: (rule, value, callback) => {
            if (value === "") {
              callback(new Error("请" + this.title + "!"));
            } else if (value < 0.01 || value > 100 || isNaN(value)) {
              callback(new Error("请输入0.01~100之间的数值!"));
            } else if (
              String(value).length > String(Number(value).toFixed(2)).length
            ) {
              callback(new Error("请保留2位小数"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        }
      }
    };
  },
  methods: {
    confirm() {
      this.$refs.ratioForm.validate(valid => {
        if (valid) {
          this.$emit("confirm", this.ratioData.ratio);
        }
      });
    },
    close() {
      this.$emit("update:visible", false);
      this.propVisible = false;
      this.$refs.ratioForm.resetFields();
    }
  }
};
</script>